﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.IdentityModel.Tokens;
using PublicClass;
using S.Breeding.Infrastructure;
using System.Text;

namespace S.Breeding.Read.Api.Extensions
{
    public static class ServicesCollectionExtensions
    {
        /// <summary>
        /// 注册JWT
        /// </summary>
        /// <param name="collection"></param>
        /// <param name="builder"></param>
        public static void AddJWT(this IServiceCollection collection, WebApplicationBuilder builder)
        {
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    //取出私钥
                    var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]);
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        //验证发布者
                        ValidateIssuer = true,
                        ValidIssuer = builder.Configuration["Authentication:Issuer"],
                        //验证接收者
                        ValidateAudience = true,
                        ValidAudience = builder.Configuration["Authentication:Audience"],
                        //验证是否过期
                        ValidateLifetime = true,
                        //验证私钥
                        IssuerSigningKey = new SymmetricSecurityKey(secretByte)
                    };
                });
        }

        /// <summary>
        /// 注册接口
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddServices(this IServiceCollection services)
        {
            services.AddScoped<EFDbContext>();

            services.AddTransient(typeof(IRepository<>), typeof(BaseRepository<>));

            services.AddTransient(typeof(PageInfo<>));

            services.AddScoped<IdentityUser>();

            return services;
        }
    }
}
